/**create by liuhua at 2019年5月22日 下午4:47:38**/
package com.star.truffle.gateway.filter;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

import java.util.Arrays;
import java.util.stream.Collectors;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

public class StripPrefixGatewayFilter implements GatewayFilter, Ordered {

  private int parts;
  
  public StripPrefixGatewayFilter(int parts) {
    this.parts = parts;
  }
  
  @Override
  public int getOrder() {
    return -1;
  }

  @Override
  public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    ServerHttpRequest request = exchange.getRequest();
    addOriginalRequestUrl(exchange, request.getURI());
    String path = request.getURI().getRawPath();
    String newPath = "/"
        + Arrays.stream(StringUtils.tokenizeToStringArray(path, "/"))
            .skip(parts).collect(Collectors.joining("/"));
    newPath += (newPath.length() > 1 && path.endsWith("/") ? "/" : "");
    ServerHttpRequest newRequest = request.mutate().path(newPath).build();

    exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

    return chain.filter(exchange.mutate().request(newRequest).build());
  }

  
}
